<template>
  <!-- 蓝牙打印机连接组件 -->
  <view class="bluetooth-printing">
    <flex class="page-label">
      {{ status == 1 ? '蓝牙设置' : '打印' }}
    </flex>
    <view class="page-content">
      <!-- 当前蓝牙状态 -->
			<flex class="uni-form-item uni-column" justify="space-between">
				<view class="uni-label">当前蓝牙状态: </view>
				<flex class="uni-input-text" justify="flex-end">
          <view class="explain" v-if="!isEnabled">未开启</view>
          <view class="explain" v-else>已开启</view>
				</flex>
			</flex>
      <!-- 立即打印 -->
      <flex class="uni-form-item uni-column" justify="space-between" v-if="status == 2">
        <view class="uni-label">打印: </view>
        <button style="margin: 0" type="primary" size="mini" @click="myClick('立即打印')">
          立即打印
        </button>
      </flex>
      <!-- 可用设备 -->
      <flex 
        class="uni-form-item uni-column" 
        direction="column" 
        align="flex-start"
      >
        <view class="uni-label">附近蓝牙设备: </view>
        <view class="list-explain" v-if="!devices.length && !isEnabled">请先开启手机蓝牙再重新打开本组件</view>
        <view class="list-explain" v-else-if="!devices.length">暂无</view>
        <!-- <pre>{{ devices }}</pre> -->
        <template v-else>
          <flex 
            class="devices-item" 
            v-for="(item, i) in devices"
            :key="i" 
            justify="space-between"
          >
            <view>{{ item.name || '未知设备' }}</view>
            <button v-if="item.deviceId == deviceInfo.connId" style="margin: 0" disabled size="mini">
              设备已连接
            </button>
            <button v-else style="margin: 0" type="primary" size="mini" @click="onConn(item)">
              连接设备
            </button>
          </flex>
        </template>
      </flex>
    </view>
  </view>
</template>
<script>
var tsc = require('../../utils/gprint/tsc.js')
var esc = require('../../utils/gprint/esc.js')

export default {
  name: 'BluetoothPrinting',
  props: {
    status: {
      type: Number,
      default: 1 // 1: setting，2: printing
    }
  },
  components: {},
  computed: {},
  data() {
    return {
      isEnabled: false, // 蓝牙开关
      devices: [], // 附近蓝牙设备列表
      deviceInfo: {
        connId: '',
        currDev: '',
      }
    };
  },
  methods: {
    // 蓝牙开关
    isEnabledChange(val) {
      this.isEnabled = val
      if (this.isEnabled) {
        // 开启蓝牙
        this.blueadapterOpen('open')
      }
    },

    // 蓝牙状态检查
    blueadapterCheck() {
      const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter') // 引入Java 蓝牙类
      const blueadapter = BluetoothAdapter.getDefaultAdapter()
      // 判断蓝牙是否开启
      if (blueadapter) {
        this.isEnabled = blueadapter.isEnabled()
        this.searchBle()
        uni.getStorage({
          key: 'deviceInfo',
          success: (res) => {
            this.deviceInfo = res.data
          }
        })
      } else {
        this.deviceInfo = {
          connId: '',
          currDev: ''
        }
        uni.setStorage({
          key: 'deviceInfo',
          data: this.deviceInfo
        })
      }
      uni.onBLEConnectionStateChange(() => {
        this.isEnabled = false
      })
    },

    // 搜索附近蓝牙设备
    searchBle() {
      this.devices = []
      uni.openBluetoothAdapter({
        success: (res) => {
          this.onDevice()
          // 获取 蓝牙模块生效期间所有搜索到的蓝牙设备
          uni.getBluetoothAdapterState({
            success: (res) => {
              if (res.available) {
                // 蓝牙适配器是否处于搜索状态
                if (res.discovering) {
                  // 关闭蓝牙搜索
                  this.stopFindBule()
                }
                //搜索蓝牙，开始搜寻附近的蓝牙外围设备
                uni.startBluetoothDevicesDiscovery({
                  success(res) {
                    console.log(res)
                  }
                })
              } else {
                this.devices()
                this.isEnabled = false
                uni.showToast({title: '蓝牙状态不可用', icon: 'error'})
              }
            }
          })
        },
      })
    },

    stopFindBule() {
      console.log("停止搜寻附近的蓝牙设备---------------")
      uni.stopBluetoothDevicesDiscovery({
        success(res) {
          console.log(res)
        }
      })
    },

    // 监听新找到的新设备的事件
    onDevice() {
      console.log("监听寻找到新设备的事件---------------")
      uni.onBluetoothDeviceFound((devices) => {
        let re = JSON.parse(JSON.stringify(devices))
        let name = re.devices[0].name
        if (name != "未知设备") {
          let deviceId = re.devices[0].deviceId
          this.devices.push({
            name: name,
            deviceId: deviceId,
            services: []
          })
        }
      })
    },

    blueadapterOpen(openStatus = true) {
      const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter') // 引入Java 蓝牙类
      if (openStatus) {
        const blueadapter = BluetoothAdapter.getDefaultAdapter();
        if (blueadapter != null) {
          // 开启蓝牙
          this.isEnabled = true
          uni.showToast({title: '蓝牙已开启', icon: 'success'})
          blueadapter.enable()
        } else {
          this.isEnabled = false
        }
      }
    },

    // 连接蓝牙
    onConn(item, callBack = () => {}) {
      console.log("连接蓝牙---------------" + item.deviceId)
      let deviceId = item.deviceId
      uni.createBLEConnection({
        deviceId: deviceId,
        complete: (res) => {
          if (res.errMsg == "createBLEConnection:ok") {
            this.deviceInfo = {
              connId: deviceId,
              currDev: item
            }
            uni.setStorage({
              key: 'deviceInfo',
              data: this.deviceInfo
            })
            uni.showToast({title: '设备连接成功', icon: 'success'})
            setTimeout(() => {
              console.log('deviceId----2', deviceId)
              this.getBLEServices(deviceId, callBack)
            }, 2000)
          }
        }
      })
    },

    // 获取蓝牙设备所有服务
    getBLEServices(_deviceId, callBack = () => {}) {
      let deviceId = _deviceId
      uni.getBLEDeviceServices({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: deviceId,
        complete: (res) => {
          let serviceId = ""
          console.log('res---', res)
          console.log('length---', res.services.length)
          for (var s = 0; s < res.services.length; s++) {
            serviceId = res.services[s].uuid
            uni.getBLEDeviceCharacteristics({
              // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
              deviceId: deviceId,
              // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
              serviceId: serviceId,
              success: (data) => {
                let re = JSON.parse(JSON.stringify(data))
                let uuid = ''
                for (let c = 0; c < re.characteristics.length; c++) {
                  if (re.characteristics[c].properties.write == true) {
                    uuid = re.characteristics[c].uuid
                    for (let index in this.devices) {
                      if (this.devices[index].deviceId == deviceId) {
                        this.devices[index].services.push({
                          serviceId: serviceId,
                          characteristicId: uuid
                        })
                        break
                      }
                    }
                    // 开始打印回调
                    callBack({
                      deviceId,
                      serviceId,
                      characteristicId: uuid
                    })
                  }
                }
              }
            })
          }
        }
      })
    },

    senBlData(deviceId, serviceId, characteristicId,uint8Array) {
      console.log('************deviceId = [' + deviceId + ']  serviceId = [' + serviceId + '] characteristics=[' +characteristicId+ "]")
      console.log('************uint8Array=' + uint8Array)
      let uint8Buf = Array.from(uint8Array);
      function split_array(datas,size){
        var result = {};
        var j = 0
        for (var i = 0; i < datas.length; i += size) {
          result[j] = datas.slice(i, i + size)
          j++
        }
        console.log(result)
        return result
      }
      let sendloop = split_array(uint8Buf, 20);
      // console.log(sendloop.length)
      function realWriteData(sendloop, i) {
        var data = sendloop[i]
        if(typeof(data) == "undefined"){
          return
        }
        console.log("第【" + i + "】次写数据"+data)
        var buffer = new ArrayBuffer(data.length)
        var dataView = new DataView(buffer)
        for (var j = 0; j < data.length; j++) {
          dataView.setUint8(j, data[j]);
        }
        uni.writeBLECharacteristicValue({
          deviceId,
          serviceId,
          characteristicId,
          value: buffer,
          success(res) {
            realWriteData(sendloop, i + 1);
          }
        })
      }
      var i = 0;
      realWriteData(sendloop, i);
    },
    
    myClick(type, data) {
      switch (type) {
        case '立即打印':
          uni.navigateTo({ url: '/pages/bluetooth/bluetooth' })
          return
          if (!this.isEnabled) {
            uni.showToast({title: '蓝牙状态不可用', icon: 'error'})
            return
          }
          let item = this.devices.find(v => {
            return v.deviceId == this.deviceInfo.connId
          })
          console.log('item---', item)
          this.onConn(item, data => {
            let deviceId = data.deviceId;
            let serviceId = data.serviceId;
            let characteristicId = data.characteristicId;
            let command = esc.jpPrinter.createNew()
            command.init()
            command.setText('\r\n\r\n下单小结\r\n订单信息：\r\n订单编号：YH-1212122121\r\n订单号码：3379*100，56*100，3730*200\r\n订单金额：￥160.00\r\n订单日期：2023/02/27 11：00\r\n\r\n\r\n\r\n');
            command.setPrintAndFeedRow(1)
            this.senBlData(deviceId, serviceId, characteristicId, command.getData())
          })
          break;
        default:
          break;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.bluetooth-printing {
  padding: 0.8rem;
  .page-content {
    max-height: 60vh;
    overflow: auto;
  }
  .uni-form-item + .uni-form-item {
    padding-top: 1.5rem;
    border-top: 1px solid #d0d0d0;
  }
  .uni-input-text {
    width: 10rem;
  }
  .devices-item {
    padding: 0.5rem 0;
    width: 100%;
  }
  .list-explain {
    margin: 2rem 0;
    width: 100%;
    text-align: center;
    color: #7b7b7b;
  }
}
</style>
